<script setup lang="ts">
import { ref, watch } from 'vue';
import { ElDialog, ElTree, ElButton, ElCheckbox } from 'element-plus';
import { $t } from '@/locales';
import { queryMenuPermission, queryPermissionIdsWithRoleId, add } from '@/service/api/system-manage';

// Props
const props = defineProps({
  visible: Boolean,
  roleId: [Number, String]
});

// Emits
const emit = defineEmits(['update:visible', 'close', 'success']);

// State
const loading = ref(false);
const submitLoading = ref(false);
const permissionTree = ref([]);
const checkedPermissionIds = ref([]);
const fetchError = ref(false);

// Tree config
const defaultProps = {
  children: 'children',
  label: 'title'
};

// Methods
function closeDialog() {
  emit('update:visible', false);
  emit('close');
}

async function loadPermissionTree() {
  loading.value = true;
  fetchError.value = false;
  
  try {
    const res = await queryMenuPermission();
    permissionTree.value = Array.isArray(res?.data) ? res.data : [];
    console.log('Permission tree loaded:', permissionTree.value.length, 'items');
  } catch (error) {
    console.error('Failed to load permission tree:', error);
    fetchError.value = true;
  } finally {
    loading.value = false;
  }
}

async function loadCheckedPermissions() {
  if (!props.roleId) return;
  
  const roleId = Number(props.roleId);
  loading.value = true;
  
  try {
    const res = await queryPermissionIdsWithRoleId(roleId);
    checkedPermissionIds.value = Array.isArray(res?.data) 
      ? res.data.map(id => Number(id)).filter(Boolean)
      : [];
    console.log('Checked permissions loaded:', checkedPermissionIds.value.length, 'items');
  } catch (error) {
    console.error('Failed to load role permissions:', error);
    fetchError.value = true;
  } finally {
    loading.value = false;
  }
}

function handleCheck(_data, checked) {
  if (checked?.checkedKeys) {
    checkedPermissionIds.value = Array.isArray(checked.checkedKeys)
      ? checked.checkedKeys.map(id => Number(id)).filter(Boolean)
      : [];
  }
}

async function handleSubmit() {
  if (!props.roleId) {
    window.$message?.warning('请选择角色');
    return;
  }
  
  submitLoading.value = true;
  
  try {
    const params = {
      roleId: Number(props.roleId),
      permissionIds: checkedPermissionIds.value
    };
    
    const result = await add(params);
    
    if (result) {
      window.$message?.success('权限更新成功');
      emit('success');
      closeDialog();
    } else {
      window.$message?.error('提交失败');
    }
  } catch (error) {
    console.error('提交权限配置失败:', error);
    window.$message?.error('提交失败');
  } finally {
    submitLoading.value = false;
  }
}

function refreshData() {
  checkedPermissionIds.value = [];
  permissionTree.value = [];
  loadPermissionTree();
  loadCheckedPermissions();
}

// Watch for dialog visibility
watch(() => props.visible, (val) => {
  console.log('Dialog visibility changed:', val);
  if (val) {
    refreshData();
  }
});

// Watch for role ID changes
watch(() => props.roleId, (val, oldVal) => {
  console.log('Role ID changed from', oldVal, 'to', val);
  if (props.visible && val !== oldVal) {
    refreshData();
  }
});
</script>

<template>
  <div>
    <el-dialog
      v-model="props.visible"
      title="编辑按钮权限"
      width="800px"
      destroy-on-close
      @closed="closeDialog"
    >
      <div v-loading="loading" class="permission-container">
        <div v-if="fetchError" class="flex-center h-full">
          <div class="text-center">
            <div class="text-red-500 text-xl mb-4">操作失败</div>
            <div class="mb-4">获取权限数据失败，请刷新重试</div>
            <el-button type="primary" @click="refreshData">重新加载</el-button>
          </div>
        </div>
        
        <div v-else class="permission-content">
          <!-- Left categories -->
          <div class="category-list">
            <div class="category-item">route.category</div>
            <div class="category-item highlight">首页</div>
            <div class="category-item">route.xs-goods</div>
            <div class="category-item">关于</div>
            <div class="category-item">代码生成</div>
            <div class="category-item">字典管理</div>
            <div class="category-item">菜单管理</div>
            <div class="category-item">用户管理</div>
          </div>
          
          <!-- Right permissions -->
          <div class="permissions-area">
            <!-- Header row for page data -->
            <div class="section-header">
              <div class="header-text red-text">页面效果</div>
            </div>
            
            <!-- Permission rows -->
            <div class="permission-row">
              <el-checkbox>用户详情1</el-checkbox>
              <el-checkbox>更新个人资料</el-checkbox>
              <el-checkbox>用户路由</el-checkbox>
              <el-checkbox>数据字典子项 Map 结构</el-checkbox>
            </div>
            
            <div class="permission-row">
              <el-checkbox>学生列表</el-checkbox>
            </div>
            
            <!-- Subdata section -->
            <div class="section-header">
              <div class="header-text red-text">子类数据</div>
            </div>
            
            <!-- More permissions -->
            <div class="permission-row">
              <el-checkbox>获取代码生成表管理列表</el-checkbox>
              <el-checkbox>新增代码生成表</el-checkbox>
              <el-checkbox>编辑更新代码生成表</el-checkbox>
            </div>
            
            <div class="permission-row">
              <el-checkbox>删除代码生成表</el-checkbox>
              <el-checkbox>生成代码</el-checkbox>
            </div>
            
            <!-- More sections from the image -->
            <div class="permission-row">
              <el-checkbox>数据字典列表</el-checkbox>
              <el-checkbox>新增字典</el-checkbox>
              <el-checkbox>更新字典</el-checkbox>
              <el-checkbox>删除字典</el-checkbox>
            </div>
            
            <div class="permission-row">
              <el-checkbox>数据字典子项列表</el-checkbox>
              <el-checkbox>新增字典子项</el-checkbox>
              <el-checkbox>更新字典子项</el-checkbox>
              <el-checkbox>删除字典子项</el-checkbox>
            </div>
            
            <div class="permission-row">
              <el-checkbox>菜单管理列表</el-checkbox>
              <el-checkbox>新增菜单</el-checkbox>
              <el-checkbox>更新菜单</el-checkbox>
              <el-checkbox>删除菜单</el-checkbox>
            </div>
            
            <div class="permission-row">
              <el-checkbox>权限按钮管理列表</el-checkbox>
              <el-checkbox>新增权限按钮</el-checkbox>
              <el-checkbox>更新权限按钮</el-checkbox>
              <el-checkbox>删除权限按钮</el-checkbox>
            </div>
            
            <div class="permission-row">
              <el-checkbox>用户管理列表</el-checkbox>
              <el-checkbox>新增用户</el-checkbox>
              <el-checkbox>更新用户</el-checkbox>
              <el-checkbox>删除用户</el-checkbox>
            </div>
            
            <div class="permission-row">
              <el-checkbox>重置密码</el-checkbox>
              <el-checkbox>即时设置</el-checkbox>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="closeDialog">取消</el-button>
          <el-button 
            type="primary" 
            :loading="submitLoading" 
            @click="handleSubmit"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.permission-container {
  height: 500px;
  overflow: auto;
}

.permission-content {
  display: flex;
  height: 100%;
}

.category-list {
  width: 200px;
  border-right: 1px solid #333;
  background-color: #2a2a2a;
}

.category-item {
  padding: 15px;
  color: #fff;
  cursor: pointer;
}

.category-item.highlight {
  background-color: #333;
}

.permissions-area {
  flex: 1;
  padding: 0;
}

.section-header {
  background-color: #333;
  padding: 10px 0;
  text-align: center;
  margin-bottom: 10px;
}

.header-text {
  color: #fff;
}

.red-text {
  color: #f56c6c;
}

.permission-row {
  display: flex;
  padding: 10px 20px;
  flex-wrap: wrap;
  border-bottom: 1px solid #3a3a3a;
}

.permission-row :deep(.el-checkbox) {
  margin-right: 50px;
  margin-bottom: 10px;
  flex: 0 0 auto;
  color: #fff;
}

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.h-full {
  height: 100%;
}

.flex {
  display: flex;
}

.justify-end {
  justify-content: flex-end;
}

.text-center {
  text-align: center;
}

.text-red-500 {
  color: #f56c6c;
}

.text-xl {
  font-size: 1.25rem;
}

.mb-4 {
  margin-bottom: 1rem;
}
</style> 